<?php
/**
 * $Author: BEESSHOP $
 * ============================================================================
 * ============================================================================
 */
namespace app\module\controllers;

use app\models\AmountRecorder;
use app\models\DiscountRecorder;
use app\models\GoodsRecorder;
use app\models\NewRecorder;
use app\models\NewuserRecorder;
use app\models\OrderRecorder;
use app\models\PurchaseRecorder;
use app\models\VipRecorder;
use app\models\YxnumRecorder;

class CarController extends BaseController{
    public $vip;

    public function beforeAction($action)
    {
        if(!$this->check_login()){
            $result = ['result'=>'login_error','data'=>'请先登录'];
            echo json_encode($result);
            return false;
        }
        //vip
        if($this->user->vip_time>time()){
            $this->vip=VipRecorder::find()->where('id='.$this->user->vip)->one();
        }
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }


    public function actionGoods(){
        $post = \Yii::$app->request->post('goods');
        $address = \Yii::$app->request->post('address');
        $address_info = $this->get_send_time($address);
        $result = $this->getGoods($post,$address_info);
        $result['send_time'] = \Yii::$app->params['send_time'];

        return json_encode($result,JSON_NUMERIC_CHECK);
    }


    public function getGoods($post,$address){
        $goods = $post;
        if(!is_array($goods)){
            $result = ['result'=>0,'data'=>'参数错误，请重新操作'];
            return $result;
        }
        if(count($goods)<=0){
            $result = ['result'=>0,'data'=>'请先添加商品'];
            return $result;
        }
        $list=[];//有效商品列表
        $error_list=[];//无效商品
        $is_new=0;//新人购使用,同一商品只能使用1次
        $discount_id=0;//满件使用,同一商品只能使用1次
        $purchase_id=0;//限时购使用,同一商品只能使用1次
        $goods_attr=[];//最后得到的每个商品
        $total_price=0;//支付金额，活动可以叠加
        $hd_price=[];//活动的优惠
        $new_user_num_arr=[];//新人购活动参与数量
        $purchase_user_num_arr=[];//限时购活动参与数量
        $purchase_arr=[];//返回的活动数据
        $new_user_arr=[];//返回的活动数据
        $is_new=false;//标记只获取一次记录
        $is_purchase=false;//标识限时购
        $amount_arr=[];//满额数组
        $err_info=[];//保存错误信息，统一显示
        $is_ck=0;//是否有选择的商品

        foreach($goods as $k=>$v){
            $model = GoodsRecorder::find()->select(['id','goods_name','goods_price','goods_hd_price','goods_num','thumb_pic','goods_unit',
                'specs_value','specs_attr','new_id','discount_id','purchase_id','amount_id'])->where('id=:id',[':id' => $v['id']])->andWhere('is_down=0')
                ->one();

            $arr=[];
            //判断是否有商品
            if(empty($model)){
                $arr['id']=$v['id'];
                $arr['goods_name']="下架商品，请删除";
                $arr['thumb_pic'] = \Yii::$app->params['non_thumb_pic'];
                $arr['error_info'] = "不存在该商品，请删除";
                if($v['ck']) {
                    $err['name'] = "不存在商品";
                    $err['info'] = "商品可能已经下架，请重新操作";
                    $err_info[] = $err;
                }
                $error_list[]=$arr;
                $arr['ck'] = $k;
                continue;
            }
            $arr['id']=$model->id;
            $arr['goods_name']=$model->goods_name;
            $model->thumb_pic = \Yii::$app->params['base_url'].$model->thumb_pic;
            $arr['thumb_pic'] = $model->thumb_pic;
            $arr['error_info'] = '';
            $arr['attr'] = [];
            $attr_value = empty($model->specs_value)?[]:json_decode($model->specs_value,true);//属性值
            $specs = empty($model->specs_attr)?[]:json_decode($model->specs_attr,true);//属性列表

            if($model->goods_num<=0){
                $arr['error_info'] = "商品库存不足";
                if($v['ck']) {
                    $err['name'] = "商品:" . $model->goods_name;
                    $err['info'] = "库存不足";
                    $err_info[] = $err;
                }
                $arr['ck'] = $k;
                $error_list[]=$arr;
                continue;
            }
            //获取属性商品
            if($v['attr_id']>=0){
                if($v['attr_id']>=count($attr_value)){
                    $arr['error_info'] = "该商品的类型已下架，请更换其它商品类型";
                    if($v['ck']) {
                        $err['name'] = "商品:" . $model->goods_name;
                        $err['info'] = "类型已下架，请更换其它商品类型";
                        $err_info[] = $err;
                    }
                    $arr['ck'] = $k;
                    $error_list[]=$arr;
                    continue;
                }
                $goods_attr_value = $attr_value[$v['attr_id']];

                $num=0;
                if($goods_attr_value['num']<=0){
                    $arr['error_info'] = "属性商品库存不足，请更换其他商品类型";
                    $arr['attr'] = $specs[$v['attr_id']];
                    if($v['ck']) {
                        $err['name'] = "商品:" . $model->goods_name;
                        $err['info'] = "库存不足，请更换其它商品类型";
                        $err_info[] = $err;
                    }
                    $arr['ck'] = $k;
                    $error_list[]=$arr;
                    continue;
                }
                if($v['num']>$goods_attr_value['num']){//商品数量超出库存
                    $v['num'] = $goods_attr_value['num'];
                    $arr['error_info'] = "商品库存不足";
                    $err_info[]=$err;
                }
                $arr['attr'] = $specs[$v['attr_id']];
                $arr['goods_num'] = $v['num'];
//                $arr['price'] = $goods_attr_value['price'];
//                $arr['hd_price'] = $goods_attr_value['hd_price'];
                $arr['goods_price'] = empty($goods_attr_value['price'])?0:$goods_attr_value['price'];;
                $arr['ck'] = $k;
                $arr['num'] = $goods_attr_value['num'];
            }else{//非属性商品
                if($v['num']>$model->goods_num){//超出库存
                    $arr['error_info'] = "商品库存不足";
                    if($v['ck']) {
                        $err['name'] = "商品:" . $model->goods_name;
                        $err['info'] = "库存不足";
                        $err_info[] = $err;
                    }
                    $arr['goods_num']=$model->goods_num;
                }else{
                    $arr['goods_num'] = $v['num'];
                }
//                $arr['price'] = $model->goods_price;
//                $arr['hd_price'] = $model->goods_hd_price;
                $arr['goods_price'] = $model->goods_price;
                $arr['ck'] = $k;
                $arr['num'] = $model->goods_num;//库存
            }


            $hd_xg_num=0;//活动数量
            $else_num=$arr['goods_num'];
            $total_hd_price=0;//活动总金额
            $hd_arr['title'] = $model->goods_name;
            $yx=[];//营销活动id,1-优惠券，2-满件减，3-满额减，4-限时购，5-新人购

            if($model->new_id){
                $hd_arr['name']='新人购';
                $hd_arr['price']=0;
                $hd_arr['info']="";
                //判断是否还有活动
                $new_model = NewRecorder::find()->where('id='.$model->new_id)->andWhere('status=0')->one();
                if(!$new_model){
//                    $arr['error_info']="";
                }else{
                    //获取已使用的活动数量
                    if(!in_array($model->new_id,$new_user_arr)){
                        $use_num_model = NewuserRecorder::find()->where('user_id='.$this->user->id)->andWhere('hd_id='.$model->new_id)->andWhere('hd_type=0')->one();
                        $new_user_num_arr[]=empty($use_num_model)?0:$use_num_model->num;
                        $new_user_arr[]=$model->new_id;
                    }
                    $user_index = array_search($model->new_id,$new_user_arr);
                    $new_user_num = $new_user_num_arr[$user_index];
                    $sy_num =($new_user_num<0)?0:$new_model->g_limit-$new_user_num;
                    if($sy_num>0){
                        if($v['ck']) {
                            if (($else_num - $sy_num) < 0) {
                                $hd_arr['price'] = ($else_num * $arr['goods_price'] * (10 - $new_model->reduce) * 10) / 100;
                                $hd_arr['price'] = sprintf("%.2f", $hd_arr['price']);
                                $total_hd_price += ($else_num * $arr['goods_price'] * $new_model->reduce * 10) / 100;

                                $new_user_num += $else_num;//更新新人购次数
                                $else_num = $else_num - $arr['goods_num'];
                                $arr['error_info'] = "比加入前省" . $hd_arr['price'] . "元";

                            } else {
                                $hd_arr['price'] = $sy_num * ($arr['goods_price'] * (10 - $new_model->reduce) * 10) / 100;
                                $hd_arr['price'] = sprintf("%.2f", $hd_arr['price']);
                                $total_hd_price += $sy_num * ($arr['goods_price'] * $new_model->reduce * 10) / 100;

                                $else_num = $else_num - $sy_num;//剩余可以参加其它活动的数量
                                $new_user_num += $sy_num;
                                $arr['error_info'] = "比加入前省" . $hd_arr['price'] . "元";
//                            $arr['goods_price'] = $arr['hd_price'];
                            }

                            $new_user_num_arr[$user_index] = $new_user_num;
                            //记录参与的活动
                            $yx_arr['type'] = 5;
                            $yx_arr['id'] = $new_model->id;
                            $yx[] = $yx_arr;
                        }
                    }else{
                        $new_user_num_arr[$user_index]=-1;
                        $hd_arr['info']="本次新人购次数0";
                    }
                    if($v['ck']){
                        $hd_price[] = $hd_arr;
                    }

                }
            }


                if($model->purchase_id){
                    $hd_arr['name'] = '限时购';
                    $hd_arr['price']=0;
                    $hd_arr['info']="";
                    //获取活动
                    $new_model = PurchaseRecorder::find()->where('id='.$model->purchase_id)->andWhere('status=0')->one();
                    if(!$new_model){
//                        return [];
                    }
                    if($new_model->endtime<time()){
//                        return [];
                    }else{
                        //获取已使用的活动数量
                        if(!in_array($model->purchase_id,$purchase_arr)){
                            $use_num_model = NewuserRecorder::find()->where('user_id='.$this->user->id)->andWhere('hd_id='.$model->purchase_id)->andWhere('hd_type=1')->one();
                            $purchase_user_num_arr[]=empty($use_num_model)?0:$use_num_model->num;
                            $purchase_arr[]=$model->purchase_id;

                        }
                        $user_index = array_search($model->purchase_id,$purchase_arr);
                        $purchase_user_num = $purchase_user_num_arr[$user_index];

                        $p_num = ($purchase_user_num<0)?0:$new_model->g_limit-$purchase_user_num;
                        if($p_num){
                            if($v['ck']) {


                                if ($else_num >= $p_num) {
                                    $hd_arr['price'] = $p_num * ($arr['goods_price'] * (10 - $new_model->reduce) * 10) / 100;
                                    $hd_arr['price'] = sprintf("%.2f", $hd_arr['price']);
                                    $total_hd_price += $p_num * ($arr['goods_price'] * $new_model->reduce * 10) / 100;
                                    $else_num = $else_num - $p_num;
                                    $arr['error_info'] = "比加入前省" . $hd_arr['price'] . "元";
                                    $purchase_user_num += $p_num;//更新使用次数
                                } else {
                                    $hd_arr['price'] = $else_num * ($arr['goods_price'] * (10 - $new_model->reduce) * 10) / 100;
                                    $hd_arr['price'] = sprintf("%.2f", $hd_arr['price']);
                                    $total_hd_price += $else_num * ($arr['goods_price'] * $new_model->reduce * 10) / 100;
                                    $arr['error_info'] = "再购买" . ($p_num - $else_num) . "件，可以省" . sprintf("%.2f", ($p_num - $else_num) * ($arr['goods_price'] * (10 - $new_model->reduce) * 10) / 100) . "元";
                                    $purchase_user_num += $else_num;//更新使用次数
                                    $else_num = 0;
                                }
                                $purchase_user_num_arr[$user_index] = $purchase_user_num;
                                //记录参与的活动
                                $yx_arr['type'] = 4;
                                $yx_arr['id'] = $new_model->id;
                                $yx[] = $yx_arr;

                            }
                        }else{
                            $purchase_user_num_arr[$user_index]=-1;
                            $hd_arr['info']="本次限时购次数0";
                        }


                        if($v['ck']) {
                            $hd_price[] = $hd_arr;
                        }
                    }

                }


                if($model->discount_id){
                    $hd_arr['name']='满件减';
                    $hd_arr['price']=0;
                    $hd_arr['info']="";
                    //判断是否还有活动
                    $new_model = DiscountRecorder::find()->where('id='.$model->discount_id)->andWhere('status=0')->one();
                    if(!$new_model){
//                        $arr['error_info']="";
                    }else if(!empty($else_num)){
//                        $arr['goods_price'] = $arr['price'];

                        $content = json_decode($new_model->content,true);
                        $d_num=0;
                        $d_price=0;
                        foreach($content as $dv){
                            if(empty($else_num)){
                                $arr['error_info'] = "再购买".$dv['count']."件,可以省".sprintf("%.2f",($dv['count']*$arr['goods_price']*(10-$dv['reduce'])*10)/100)."元";
                                break;
                            }
                            if($dv['count']>$else_num){
                                $dnum = $dv['count']-$else_num;
                                if($dnum>0){
                                    $arr['error_info'] = "再购买".($dnum)."件,可以省".sprintf("%.2f",($dv['count']*$arr['goods_price']*(10-$dv['reduce'])*10)/100)."元";
                                }
                                break;
                            }else{
                                $d_num=$dv['count'];
                                $hd_arr['price'] = sprintf("%.2f",($dv['count']*$arr['goods_price']*(10-$dv['reduce'])*10)/100);
                                $d_price =sprintf("%.2f",($dv['count']*$arr['goods_price']*$dv['reduce']*10)/100);
                            }
                        }
                        if($d_price){
                            //记录参与的活动
                            $yx_arr['type'] = 2;
                            $yx_arr['id'] = $new_model->id;
                            $yx[]=$yx_arr;
                        }
                        $total_hd_price +=$d_price;
                        $else_num = $else_num-$d_num;
                        if($v['ck']){
                            $hd_price[]=$hd_arr;
                        }
                    }
                }


                if($model->amount_id){
                    $amount_model = AmountRecorder::find()->where('id='.$model->amount_id)->andWhere("status=0")->one();
                    if($amount_model){
                        if($v['ck']) {
                            $arr['total_price'] = $arr['goods_price'] * $else_num + $total_hd_price;
                        }else{
                            $arr['total_price']=0;
                        }
                         $arr['amount_id'] = $amount_model->id;
                         if(!in_array($amount_model->id,$amount_arr)){
                             $amount_arr[]=$amount_model->id;
                         }
                    }
                }


            if($v['ck']){
                $total_price += $arr['goods_price']*$else_num+$total_hd_price;
                $is_ck=1;
            }


            $list[]=$arr;
        }//循环结束


        if(count($amount_arr)){
            foreach($amount_arr as $k=>$v){
                $m_arr=[];
                $m_price=0;
                foreach($list as $a_k=>$a_v){
                    if($v==$a_v['amount_id']){
                        $m_arr[]=$a_v;
                        $m_price+=$a_v['total_price'];
                    }
                }
                $amount_model = AmountRecorder::find()->where('id='.$v)->andWhere("status=0")->one();
                if($m_price>=$amount_model->count){
                    $total_price = $total_price-$amount_model->reduce;
                    $return['a_info']='';
                    $hd_arr['title']="";
                    $hd_arr['info']="";
                    $hd_arr['name']=$amount_model->title;
                    $hd_arr['price']=$amount_model->reduce;
                    $hd_price[]=$hd_arr;
                    //记录参与的活动
                    $yx_arr['type'] = 3;
                    $yx_arr['id'] = $new_model->id;
                    $yx[]=$yx_arr;
                }else{
                    $return['a_info']="还差".($amount_model->count-$m_price)."元";
                    $return['amount_id'] = $amount_model->id;
                }
                $return['name']=$amount_model->title;
                $return['is_amount']=1;
                $return['list']=$m_arr;
                $return_list[]=$return;
            }
        }


        $else_arr=[];
        foreach($list as $k=>$v){
            if(!in_array($v['amount_id'],$amount_arr)) {
                $else_arr[] = $v;
            }
        }
        $return['name']="";
        $return['a_info']='';
        $return['is_amount']=0;
        $return['list']=$else_arr;
        $return_list[]=$return;




        if($error_list) {
            $return['name'] = "error";
            $return['list'] = $error_list;
            $return['is_amount'] = 0;
            $return['a_info'] = '';
            $return_list[] = $return;
        }


        if($this->user->vip&&$is_ck){
            $vip = $this->vip;
            if($vip){
                if($vip->vip_reduce>0&&$vip->vip_reduce<=10){
                    $hd_arr['info']="";
                    $hd_arr['title'] = "全部";
                    $hd_arr['price']=sprintf("%.2f",$total_price*((10-$vip->vip_reduce)*10)/100);
                    $total_price = sprintf("%.2f",$total_price*($vip->vip_reduce*10)/100);
                    $hd_arr['name']='会员折扣';
                    $hd_price[]=$hd_arr;
                }
            }

        }


        $order_else=[];
        //运费包邮
        $freight_none = ($address['is_city'])?\Yii::$app->params['freight_none']:$address['b_price'];
        $order_else['freight_none'] = $address['b_price'];
        $order_else['freight'] = $address['price'];
        $order_else['packing'] = \Yii::$app->params['packing'];
        if($total_price>=$freight_none){
            $order_else['freight_reduce']=0;
            $order_else['freight']=0;
        }else{
            $order_else['freight_reduce'] = sprintf("%.2f",($freight_none-$total_price));
        }

        $total_price = sprintf("%.2f",($total_price+$order_else['freight']+$order_else['packing']));
        if(!$is_ck){
            $total_price=0;
        }

        $result = ['result'=>1,'data'=>$return_list,"total_price"=>$total_price,'hd_price'=>$hd_price,"purchase_arr"=>$purchase_arr,"purchase_user_num_arr"=>$purchase_user_num_arr,"new_user_arr"=>$new_user_arr,"new_user_num_arr"=>$new_user_num_arr,"err_info"=>$err_info,"order_else"=>$order_else,"yx"=>$yx];
        return $result;
    }


    public function actionCkgoods(){
        $post = \Yii::$app->request->post('goods');
        $result = $this->getGoods($post);
        return json_encode($result,JSON_NUMERIC_CHECK);
    }


    public function actionOrder(){
        $post = \Yii::$app->request->post('order');
        $goods = $post['goods'];
        $address_info = $this->get_send_time($post['address']['id']);
        $result = $this->getGoods($goods,$address_info);
        if($result['result']){
            //是否有选择商品错误
            if(count($result['err_info'])>0){
                $str='';
                foreach ($result['err_info'] as $v){
                    $str.=$v['name'];
                    $str.=$v['info']."\n";
                }
                $result = ['result'=>0,'data'=>$str];
                return json_encode($result);
            }
            $model = new OrderRecorder();
            $model->addtime = time();
            $model->order_name = "NO".date("YmdHis",time()).rand(1,1000);
            $model->order_content= json_encode($result['data']);
            $model->total_price = $result['total_price'];
            $model->hd_price = json_encode($result['hd_price']);
            $model->purchase_arr = json_encode($result['purchase_arr']);
            $model->purchase_user_num_arr = json_encode($result['purchase_user_num_arr']);
            $model->new_user_arr = json_encode($result['new_user_arr']);
            $model->new_user_num_arr = json_encode($result['new_user_num_arr']);
            $model->user_id = $this->user->id;
            $model->goods_attr = json_encode($goods);
            $model->order_else = json_encode($post['order_else']);
            $model->address = json_encode($post['address']);
            $model->yx = json_encode($result['yx']);
            $model->order_info = $post['order_info'];

            if($model->save(false)){
                //记录加购信息
                $yx = $result['yx'];
                foreach($yx as $v){
                    $yx_model = new YxnumRecorder();
                    $yx_model->user_id = $this->user->id;
                    $yx_model->yx_id=$v['id'];
                    $yx_model->yx_type=$v['type'];
                    $yx_model->addtime = time();
                    $yx_model->save(false);
                }
                $result = ['result'=>1,'data'=>$model->id];
            }else{
                $result = ['result'=>0,'data'=>'生成订单发送错误，请重新操作'];
            }
        }else{
            $result = ['result'=>0,'data'=>'参数发生错误，请重新操作'];
        }
        return json_encode($result);
    }

}
